import {useState, useCallback} from 'react';

export default function useFetch(reqObj, cb){
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const fetchData = useCallback(async (body) => {
        try{
            setLoading(true);
            setError(null);
            const res = await fetch('http://localhost:1337/api/' + reqObj.url,
                {
                    method:reqObj.method || 'get',
                    headers:{
                        "Content-type":"application/json"
                    },
                    body:body? JSON.stringify({data:body}) : null
                }
            )
            if(res.ok) {
                if (reqObj.method && reqObj.method.toUpperCase() === "DELETE") {cb();return}
                const data = await res.json();
                setData(data.data);
                cb && cb();
            }else{
                throw new Error('数据加载失败')
            }
        }catch (e){
            console.log(e.message);
            setError(e.message)
        }finally {
            setLoading(false)
        }
    }, [])   // eslint-disable-line

    return{
        loading,
        error,
        data,
        fetchData
    }
}